import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:tapjoy_offerwall/tapjoy_offerwall.dart';
import '../http/http_agent.dart';
import '../service/auth_service.dart';
import '../service/user_storage_service.dart';
import '../model/user_model.dart';
import '../widgets/login_dialog.dart';
import 'setting_controller.dart';
import 'home_controller.dart';
import 'admob_controller.dart';
import 'tapjoy_controller.dart';

class AuthController extends GetxController {
  // ==================== 状态变量 ====================
  var isLoggedIn = false.obs;
  var isBindAccount = false.obs;
  var userName = ''.obs;
  var userEmail = ''.obs;
  var userPhotoUrl = ''.obs;
  var btcBalance = '0.00000000'.obs;
  var isLoading = false.obs;
  Rx<UserModel?> currentUser = Rx<UserModel?>(null);

  // ==================== 服务实例 ====================
  final GoogleSignIn _googleSignIn = GoogleSignIn(
    scopes: ['email', 'profile'],
    serverClientId:
        '624852916548-7mugjmeigkgfsohe1o6in7ueuu729c34.apps.googleusercontent.com',
  );
  final AuthService _authService = AuthService();
  final UserStorageService _storageService = UserStorageService();

  // ==================== 生命周期 ====================
  @override
  void onInit() {
    super.onInit();
  }

  // ==================== 启动登录检查 ====================
  /// 启动时登录检查（在闪屏之前调用）
  Future<bool> checkStartupLogin() async {
    try {
      // 1. 应用打开后调用登录API
      print('步骤1: 调用登录API');
      final loginResponse = await _authService.login();

      if (!loginResponse.success || loginResponse.data == null) {
        print('登录API失败: ${loginResponse.message}');
        await _storageService.clearUserData();
        return false;
      }

      // 保存用户数据并更新状态
      await _storageService.saveUser(loginResponse.data!);
      _updateUserState(loginResponse.data!);
      print('登录API成功，用户数据已保存');

      // 2. 登录API成功后调用谷歌静默登录
      print('步骤2: 调用谷歌静默登录');
      final silentResult = await signInSilentlyWithGoogle();
      print('谷歌静默登录结果: $silentResult');

      // 3. 不管静默登录成功与否都调用获取应用信息API
       print('步骤3: 调用获取应用信息API');
       final versionService = Get.find<SettingController>();
       await versionService.loadVersionInfo();
       print('应用信息API调用完成');

      // 4. 应用信息API成功后调用获取首页数据API
      print('步骤4: 调用获取首页数据API');
      final homeController = Get.find<HomeController>();
      await homeController.getHomeData();
      print('首页数据API调用完成');

      // 5. 所有API调用成功，预加载广告
      print('步骤5: 所有API调用成功，预加载广告');
      final adMobController = Get.find<AdMobController>();
      adMobController.loadRewardedAd(AdMobController.FREE_PLAN_AD_UNIT);
      // try {
      //   final tapjoyCtrl = Get.isRegistered<TapjoyController>()
      //       ? Get.find<TapjoyController>()
      //       : Get.put(TapjoyController());
      //   final String sdkKey = Platform.isAndroid
      //       ? '3ezcC4_TSSGTa712qMVDqwECxteDCeLa4OJx8vywEIzr4d6LtZlAKB-nLfsH'
      //       : 'jsh3Nk1ISqOmRGcsGq699gEB6LFTnjhQLwDLuvqrwEg1bR_MLyf14EmkJLze';
      //   final connected = await tapjoyCtrl.connect(
      //     sdkKey: sdkKey,
      //     userId: currentUser.value?.uid.toString(),
      //   );
      //   if (connected) {
      //     final String placementName = Platform.isAndroid
      //         ? 'watch offerwall'
      //         : 'BitPlanera-offerWall-Apple';
      //     await tapjoyCtrl.prefetchOfferwall(
      //       placementName: placementName,
      //       entryPoint: TJEntryPoint.entryPointMainMenu,
      //     );
      //   } else {
      //     print('Tapjoy未连接成功，跳过预取');
      //   }
      // } catch (e) {
      //   print('Tapjoy初始化失败: $e');
      // }

      // 6. 准备进入主页
      print('步骤6: 准备进入主页');
      return true;

    } catch (e) {
      print('启动登录过程出错: $e');
      await _storageService.clearUserData();
      return false;
    }
  }

  // ==================== Google 登录 ====================
  /// Google 静默登录
  Future<bool> signInSilentlyWithGoogle() async {
    try {
      print("尝试 Google 静默登录...");
      final GoogleSignInAccount? googleUser =
          await _googleSignIn.signInSilently();
      if (googleUser == null) {
        print("静默登录失败：未找到已登录用户");
        return false;
      }

      final GoogleSignInAuthentication googleAuth =
          await googleUser.authentication;
      final idToken = googleAuth.idToken;

      if (idToken == null) {
        print("静默登录失败：未获取到 idToken");
        return false;
      }

      // 发送 idToken 给服务端
      final response = await _authService.bindGoogleAccount(idToken);

      if (response.success && response.data != null) {
        await _storageService.saveUser(response.data!);
        _updateUserState(response.data!);
        isBindAccount.value = true;
        print("静默登录成功：${response.data!.displayName}");
        return true;
      } else {
        print("静默登录失败：${response.message}");
        return false;
      }
    } catch (e) {
      print("Google 静默登录出错: $e");
      return false;
    }
  }

  /// 苹果登录
  Future<bool> signInWithApple() async {
    try {
      isLoading.value = true;

      // 获取苹果登录凭证
      final credential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );

      // 获取必要的信息
      final idToken = credential.identityToken;
      final userIdentifier = credential.userIdentifier;
      final givenName = credential.givenName;
      final familyName = credential.familyName;
      final email = credential.email;

      if (idToken == null || userIdentifier == null) {
        print('苹果登录失败: 未获取到必要信息');
        _showLoginErrorMessage('login_failed'.tr);
        return false;
      }

      // 调用后端API绑定苹果账号
      final response = await _authService.bindAppleAccount(
        idToken,
        userIdentifier,
        "givenName",
        "familyName",
        "email",
      );

      if (response.success && response.data != null) {
        // 保存用户信息
        await _storageService.saveUser(response.data!);
        _updateUserState(response.data!);
        isBindAccount.value = true;
        _showLoginSuccessMessage(response.data!.displayName);
        
        // 预加载广告
        final adMobController = Get.find<AdMobController>();
        adMobController.loadRewardedAd(AdMobController.FREE_PLAN_AD_UNIT);
        
        return true;
      } else {
        _showLoginErrorMessage(response.message ?? 'login_failed'.tr);
        return false;
      }
    } catch (e) {
      print('苹果登录出错: $e');
      _showLoginErrorMessage('login_failed'.tr);
      return false;
    } finally {
      isLoading.value = false;
    }
  }

  /// 根据平台选择登录方式
  Future<bool> signInWithPlatform() async {
    if (Platform.isIOS) {
      return await signInWithApple();
    } else {
      return await signInWithGoogle();
    }
  }

  /// Google 登录主流程
  Future<bool> signInWithGoogle() async {
    print('开始 Google 登录流程');
    try {
      isLoading.value = true;

      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      if (googleUser == null) {
        // 用户取消登录
        return false;
      }

      final GoogleSignInAuthentication googleAuth =
          await googleUser.authentication;

      final idToken = googleAuth.idToken;

      if (idToken == null) {
        throw Exception("未能获取 Google idToken");
      }

      debugPrint("idToken: $idToken");

      // 发送给你自己的服务端
      final response = await _authService.bindGoogleAccount(idToken);

      if (response.success && response.data != null) {
        await _storageService.saveUser(response.data!);
        _updateUserState(response.data!);
        isBindAccount.value = true;
        _showLoginSuccessMessage(response.data!.displayName);
        return true;
      } else {
        throw Exception(response.message ?? '服务端登录失败');
      }
    } catch (error) {
      _showLoginErrorMessage(error);
      print('Google 登录错误: $error');
      return false;
    } finally {
      isLoading.value = false;
    }
  }

  // ==================== 登出相关 ====================
  Future<void> logout() async {
    try {
      isLoading.value = true;
      try {
        await _authService.logout();
      } catch (e) {
        print('服务端登出失败: $e');
      }
      await _clearAuthState();
      _showLogoutSuccessMessage();
    } catch (error) {
      print('退出登录错误: $error');
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> deleteAccount() async {
    try {
      await _clearAuthState();
      await _authService.deleteAccount();
      _showAccountDeletedMessage();
      Get.offAllNamed('/login');
    } catch (e) {
      print('Delete account error: $e');
      _showAccountDeleteErrorMessage();
    }
  }

  // ==================== 弹窗相关 ====================
  void showLoginDialog() {
    if (!isBindAccount.value) {
      Get.dialog(
        LoginDialog(),
        barrierDismissible: true,
      );
    }
  }

  // ==================== 私有辅助方法 ====================
  void _updateUserState(UserModel user) {
    currentUser.value = user;
    isLoggedIn.value = true;
    userName.value = user.nickname;
    btcBalance.value = "0.00000000";
    HttpAgent().updateUid(user.uid.toString());
    HttpAgent().updateToken(user.accessToken);
  }

  Future<void> _clearAuthState() async {
    await _googleSignIn.signOut();
    await _storageService.clearUserData();
    HttpAgent().updateUid(null);
    _resetUserState();
  }

  void _resetUserState() {
    currentUser.value = null;
    isLoggedIn.value = false;
    isBindAccount.value = false;
    userName.value = '';
    userEmail.value = '';
    userPhotoUrl.value = '';
    btcBalance.value = "0.00000000";
  }

  Future<void> _rollbackGoogleLogin() async {
    try {
      print('回滚 Google 登录状态');
      await _googleSignIn.signOut();
      _resetUserState();
      print('登录状态回滚完成');
    } catch (rollbackError) {
      print('回滚登录状态时出错: $rollbackError');
      _resetUserState();
    }
  }

  // ==================== 消息提示方法 ====================
  void _showLoginSuccessMessage(String displayName) {
    // Future.delayed(const Duration(milliseconds: 500), () {
    //   if (!Get.isSnackbarOpen) {
    //     Get.snackbar(
    //       'login_success'.tr,
    //       'welcome_back'.tr,
    //       backgroundColor: const Color(0xFF4ECDC4),
    //       colorText: Colors.white,
    //       snackPosition: SnackPosition.TOP,
    //       margin: const EdgeInsets.all(16),
    //       borderRadius: 12,
    //       duration: const Duration(seconds: 2),
    //     );
    //   }
    // });
  }

  void _showLoginErrorMessage(dynamic error) {
    Get.snackbar(
      'Tips',
      'Login failed. Please try again.',
      backgroundColor: Colors.red,
      colorText: Colors.white,
      snackPosition: SnackPosition.TOP,
      margin: const EdgeInsets.all(16),
      borderRadius: 12,
    );
  }

  void _showLogoutSuccessMessage() {
    // Get.snackbar(
    //   'logout'.tr,
    //   'logout_success'.tr,
    //   backgroundColor: const Color(0xFF4A4A4A),
    //   colorText: Colors.white,
    //   snackPosition: SnackPosition.TOP,
    //   margin: const EdgeInsets.all(16),
    //   borderRadius: 12,
    // );
  }

  void _showAccountDeletedMessage() {
    // Get.snackbar(
    //   'account_deleted_success'.tr,
    //   '',
    //   snackPosition: SnackPosition.TOP,
    //   backgroundColor: Colors.green,
    //   colorText: Colors.white,
    // );
  }

  void _showAccountDeleteErrorMessage() {
    // Get.snackbar(
    //   'Error',
    //   'Failed to delete account. Please try again.',
    //   snackPosition: SnackPosition.TOP,
    //   backgroundColor: Colors.red,
    //   colorText: Colors.white,
    // );
  }

  // ==================== Getter 方法 ====================
  bool get isNewUser => currentUser.value?.isNewUser ?? false;
  String get userId => currentUser.value?.showId.toString() ?? '';
  String get accessToken => currentUser.value?.accessToken ?? '';
}
